package com.atguigu.tingshu.user.login;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;


@LoginBean(LoginType.WX_LOGIN)
public class WxLogin implements ILogin {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private UserAccountFeignClient userAccountFeignClientl;


    @Override
    public Map<String, Object> login(LoginAccount loginAccount) {
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(loginAccount.getCode());
            String openid = sessionInfo.getOpenid();

            if (StringUtils.isBlank(openid)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }

            //根据openid去userinfo查询用户是否存在

            UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));

            if (ObjectUtils.isEmpty(userInfo)){
                //如果为空  则隐式创建用户
                userInfo=new UserInfo();
                userInfo.setWxOpenId(openid);
                userInfo.setNickname("听书书友"+new Random(10000));
                userInfo.setStatus("1");
                userInfo.setAvatarUrl("https://c-ssl.duitang.com/uploads/item/201909/27/20190927144411_yYhzX.jpeg");

                userInfoMapper.insert(userInfo);
                //初始化用户信息
                //远程调用 account模块 初始化账户表
                Result init = userAccountFeignClientl.init(userInfo.getId());
                if (init.getCode()!=200){
                    throw new GuiguException(ResultCodeEnum.SERVICE_ERROR);
                }
//                System.out.println(init.getMessage());
            }


            Map<String, Object> map = new HashMap<>();


            String token = UUID.randomUUID().toString();
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(userInfo,userInfoVo);

            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(userInfoVo.getNickname());
            redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token,userInfoVo);
            map.put("token",token);

            return map;
        } catch (WxErrorException e) {
            throw new RuntimeException(e);

        }

    }
}
